/**
 * @date 2022-5-31 0:51
 * @参考地址 http://www.javashuo.com/article/p-tpiddslh-ng.html
 * **/

import React, { FC, useEffect, useRef, useState } from 'react';

const LyricDemo: FC = () => {
  const lrc_contentRef = useRef<any>(null);
  const audioRef = useRef<any>(null);
  const [medisArray, setMedisArray] = useState<{ t?: string; c?: string }[]>(
    []
  );
  console.log(medisArray);

  useEffect(() => {
    const lrc_content = lrc_contentRef.current;
    const data: any = [];
    if (lrc_content) {
      const medis = lrc_content.value;
      const medises = medis.split('\n');
      medises.forEach((item: string, key: number) => {
        const t: string = item.substring(
          item.indexOf('[') + 1,
          item.indexOf(']')
        );
        const m: any = t.split(':')[0] || 0;
        data.push({
          t: (m * 60 + parseFloat(t.split(':')[1])).toFixed(3),
          c: item.substring(item.indexOf(']') + 1, item.length),
        });
      });

      setMedisArray(data);
    }
  }, []);

  useEffect(() => {
    const audio = audioRef.current;
    if (audio && medisArray.length) {
      let lineNo = 1;
      audio.ontimeupdate = function (event: any) {
        if (
          lineNo === medisArray.length - 1 &&
          Number(audio.currentTime.toFixed(3)) >=
            parseFloat(medisArray[lineNo].t || '')
        ) {
          lineHeight(lineNo);
        }

        if (
          parseFloat(medisArray[lineNo].t || '') <=
            Number(audio.currentTime.toFixed(3)) &&
          Number(audio.currentTime.toFixed(3)) <=
            parseFloat(medisArray?.[lineNo + 1]?.t || '')
        ) {
          lineHeight(lineNo);

          lineNo++;
        }
      };
    }
  }, [medisArray]);

  const lineHeight: (lineno: number) => void = (lineno) => {
    const ul = document.getElementById('text');
    let nowline: any;
    // 令正在唱的那一行高亮显示
    if (lineno > 0) {
      ul &&
        ul.childNodes.forEach((item: any, key) => {
          if (key === lineno) {
            item.style.color = 'red';
            nowline = item;
          } else {
            item.style.color = '';
          }
        });
    }
    // 实现文字滚动

    let _scrollTop;
    const fraction = 0.5;
    if (ul) {
      if (ul.clientHeight * fraction > nowline.offsetTop) {
        _scrollTop = 0;
      } else {
        _scrollTop = nowline.offsetTop - ul.clientHeight * fraction;
      }
      ul.scrollTop = _scrollTop;
    }
  };

  return (
    <>
      <textarea
        id="lrc_content"
        name="textfield"
        cols={70}
        rows={10}
        style={{ display: 'none' }}
        ref={lrc_contentRef}
        defaultValue="[00:00.410]大鱼 - 王若伊
[00:01.410]做词：尹约
[00:02.310]做曲：钱雷
[00:03.161]
[00:44.447]海浪无声将夜幕深深淹没
[00:51.200]漫过天空尽头的角落
[00:57.995]大鱼在梦境的缝隙里游过
[01:04.848]凝望你沉睡的轮廓
[01:10.898]看海天一色 听风起雨落
[01:17.705]执子手吹散苍茫茫烟波
[01:24.506]大鱼的翅膀 已经太辽阔
[01:32.112]我松开时间的绳索
[01:38.017]怕你飞远去
[01:41.620]怕你离我而去
[01:45.173]更怕你永远停留在这里
[01:51.876]每一滴泪水
[01:55.428]都向你流淌去
[01:59.623]倒流进天空的海底
[02:05.201]
[02:20.568]海浪无声将夜幕深深淹没
[02:27.118]漫过天空尽头的角落
[02:34.029]大鱼在梦境的缝隙里游过
[02:40.733]凝望你沉睡的轮廓
[02:47.051]看海天一色 听风起雨落
[02:53.654]执子手吹散苍茫茫烟波
[03:00.637]大鱼的翅膀 已经太辽阔
[03:08.087]我松开时间的绳索
[03:14.187]看你飞远去 看你离我而去
[03:21.039]原来你生来就属于天际
[03:27.889]每一滴泪水 都向你流淌去
[03:35.540]倒流回最初的相遇"
      ></textarea>
      <ul
        id="text"
        style={{
          overflow: 'auto',
          width: 460,
          height: 235,
          scrollBehavior: 'smooth',
        }}
      >
        {medisArray.map((item, key) => {
          return (
            <li key={key} style={{ listStyle: 'none' }}>
              {item.c}
            </li>
          );
        })}
      </ul>
      <audio
        controls
        ref={audioRef}
        src="https://webfs.tx.kugou.com/202205302349/82ce0bb65cfa33cb0514187f12576e9c/G117/M07/09/19/FYcBAFplYrKAV3QFAEQONjtwGsY679.mp3"
      ></audio>
    </>
  );
};

export default LyricDemo;
